/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * 
 * Project Name:assign-tracer
 * Create Time: 2016年2月24日 下午9:03:13
 */
package com.lenovo.lmrp.server.assigntracer.util.grap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.model.entity.TicketProcessPO;
import com.lenovo.lmrp.api.model.view.ChangedTicketVO;
import com.lenovo.lmrp.api.model.view.GrabRecode;
import com.lenovo.lmrp.server.assigntracer.repository.ARepositoryFactory;

/**
 * Randomly selected, grab a single strategy
 * 
 * @author songyz
 * @version $Id: RandomGrab.java, v 0.1 2016年2月24日 下午9:03:13 songyz Exp $
 */
public class RandomGrab implements IGrab {

	private static final long serialVersionUID = 1L;
	private final static Logger logger = LoggerFactory.getLogger(RandomGrab.class);

	private Set<GrabRecode> set = new HashSet<>();

	// 将抢单记录放入队列中
	public void put(GrabRecode grabRecode) {
		if (set.size() == 0) {
			
			new Timer().schedule(new TimerTask() {//创建定时器，执行延迟任务
				
				public void run() {
					if (logger.isDebugEnabled())
						logger.debug("Now were randomly selected: list.size=" + set.size());
					if (set.size() != 0) {
						GrabRecode recode = new ArrayList<>(set).get(new Random().nextInt(set.size()));
						// 这就是抢单的结果
						if (logger.isDebugEnabled())
							logger.debug("Randomly selected results,engineerId is " + recode.getEngineerId());

						// 调用工作流,更新工作流中的节点
						TicketProcessPO processPO = ARepositoryFactory.getFactory().getWorkflowRepository()
								.getRuningTicketProcess(grabRecode.getItsmCode(), grabRecode.getTicketId());
						Map<String, String> params2 = new HashMap<>();
						params2.put("choicedEngineer", grabRecode.getEngineerId());
						ChangedTicketVO cvo = new ChangedTicketVO();
						cvo.setFields(params2);
						ARepositoryFactory.getFactory().getIProcessService().fireProcessInstance(processPO, cvo);
					}
				}
			}, GrabFactory.GRAB_PERIOD);
		}
		set.add(grabRecode);
	}
}
